package com.ship.dispatch.service.impl;


import cn.hutool.json.JSONUtil;
import com.google.gson.Gson;

import com.ship.common.core.constant.ShipApiConstants;
import com.ship.common.core.utils.OkHttpUtil;
import com.ship.dispatch.bean.boats.ShipDashboarDataRq;
import com.ship.dispatch.service.ShipDashboarDataService;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.apache.commons.collections4.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.*;
import java.net.URL;
import java.util.Base64;
import java.util.Map;

/**
 * <b>ShipDashboarDataServiceImpl</b>
 *
 * @description: ShipDashboarDataServiceImpl <br>
 * @date: 2024/7/19 14:09 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class ShipDashboarDataServiceImpl implements ShipDashboarDataService {
    private static final Logger logger = LoggerFactory.getLogger(ShipDashboarDataServiceImpl.class);


    @Override
    public void pushGuanWuData(ShipDashboarDataRq rq) throws IOException {
        //将数据进行base64加密
        String data = encipher(rq);
//        URL url = new URL("http://zhgwcs.cnooc.com.cn/e-test-api/dashboard/shipDashboardData");
        com.alibaba.fastjson.JSONObject paramJson = new com.alibaba.fastjson.JSONObject();
        paramJson.put("data",data);
        paramJson.put("flag",getFlagEncipher(rq));
        RequestBody body = RequestBody.create(paramJson.toJSONString(), MediaType.parse("application/json"));
        Map<String, String> headers = new HashedMap<>();
        headers.put("Content-Type", "application/json;charset=UTF-8");
        headers.put("Accept","application/json");
        Object resultObj = OkHttpUtil.sendOkHttpClient("http://10.75.34.147:80/e-test-api/dashboard/shipDashboardData"
                , "POST",body,headers);
        logger.info("返回结果:{}"+ JSONUtil.parse(resultObj));
    }

//    public static void main(String[] args) throws IOException {
//        String data = "eyJ2b3lhZ2VObyI6ICIxMjM0NTYiLCJnb29kc051bSI6ICIxMjM0MyIsICJ0cmFkZVR5cGUiOiAiMSIsICAic2VsbGVyIjogIjEyMzQ0NSIsImJ1eWVyIjogIjEyMzQ1Iiwic2hpcE5h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WRlQ291bnRyeSI6IjEyMzQzIiwiZmxhZyI6IjEifQ";
//        URL url = new URL("https://zhgwcs.cnooc.com.cn/e-test-api/dashboard/shipDashboardData");
//        //第二步：打开一个通向服务地址的连接
//        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//        //第三步：设置参数
//        //3.1发送方式设置：POST必须大写
//        connection.setRequestMethod("POST");
//        //3.2设置数据格式：content-type
//        connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
//        connection.setRequestProperty("Accept","application/json");
//        connection.setRequestProperty("data",data);
//        connection.setRequestProperty("flag","MTIzMzQxMjM0NTYxMjMxMjMxMjMxMjMx");
//        //3.3设置输入输出，因为默认新创建的connection没有读写权限，
//
//        connection.setDoInput(true);
//        connection.setDoOutput(true);
//        //第五步：接收服务端响应，打印
//        int responseCode = connection.getResponseCode();
//
//        logger.info("调用接口返回结果:{}"+JSONUtil.parse(responseCode));
//        if(200 == responseCode){//表示服务端响应成功
//            //获取当前连接请求返回的数据流
//            InputStream is = connection.getInputStream();
//            InputStreamReader isr = new InputStreamReader(is);
//            BufferedReader br = new BufferedReader(isr);
//            StringBuilder sb = new StringBuilder();
//            String temp = null;
//            while(null != (temp = br.readLine())){
//                sb.append(temp);
//            }
//
//            /**
//             * 打印结果
//             */
//            logger.info("获取返回结果:{}"+JSONUtil.parse(sb.toString()));
//            try{
//                //对返回的数据进行JSON格式化
//                System.out.println(xml2Json(sb.toString()));
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//            is.close();
//            isr.close();
//            br.close();
//        }
//    }
//
//    public static com.alibaba.fastjson.JSONObject xml2Json(String xmlStr) throws DocumentException {
//        Document doc = DocumentHelper.parseText(xmlStr);
//        com.alibaba.fastjson.JSONObject json = new JSONObject();
//        dom4j2Json(doc.getRootElement(), json);
//        return json;
//    }
//    public static void dom4j2Json(Element element, JSONObject json) {
//        List<Element> chdEl = element.elements();
//        for(Element e : chdEl){
//            if (!e.elements().isEmpty()) {
//                JSONObject chdjson = new JSONObject();
//                dom4j2Json(e, chdjson);
//                Object o = json.get(e.getName());
//                if (o != null) {
//                    JSONArray jsona = null;
//                    if (o instanceof JSONObject) {
//                        JSONObject jsono = (JSONObject) o;
//                        json.remove(e.getName());
//                        jsona = new JSONArray();
//                        jsona.add(jsono);
//                        jsona.add(chdjson);
//                    }
//                    if (o instanceof JSONArray) {
//                        jsona = (JSONArray) o;
//                        jsona.add(chdjson);
//                    }
//                    json.put(e.getName(), jsona);
//                } else {
//                    if (!chdjson.isEmpty()) {
//                        json.put(e.getName(), chdjson);
//                    }
//                }
//            } else {
//                if (!e.getText().isEmpty()) {
//                    json.put(e.getName(), e.getText());
//                }
//            }
//        }
//    }

    public String encipher(ShipDashboarDataRq rq){
        Gson gson = new Gson();
        String data = gson.toJson(rq);
        logger.info("转换后的数据:{}"+data);
        String encodedText = Base64.getEncoder().encodeToString(data.getBytes());
        System.out.println("Encoded: " + encodedText);
        return encodedText;
    }

    public String getFlagEncipher(ShipDashboarDataRq rq){
        String data = rq.getShipName()+"+"+rq.getVoyageNo()+"+"+rq.getTdNo()+"+"+rq.getFlag();
        String encodedText = Base64.getEncoder().encodeToString(data.getBytes());
        System.out.println("Encoded: " + encodedText);
        return encodedText;
    }
}
